package com.swordget.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;

/***
 *  freemarker 模板工具类
 * @author liang.xu
 * @date 2021.09.16
 */
public class FreemarkerUtils {


    public static String generateString(String templateLoadingPath, String tpl, Map<String, Object> context) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        //configuration.setDirectoryForTemplateLoading(new File(templateLoadingPath));
        configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtils.class,templateLoadingPath));
        Template template = configuration.getTemplate(tpl);
        StringWriter resultStr = new StringWriter();
        configuration.setDefaultEncoding("utf-8");
        template.process(context, resultStr);
        return resultStr.toString();
    }
}